using System;
using System.Xml.XPath;

using AutoUpdateEngine.Operations;
namespace AutoUpdateEngine.Xml
{
    public class OperationBuilder
    {
        public OperationBuilder(XPathNavigator operationXml)
        {
            if (operationXml.LocalName != "operation")
                throw new ArgumentException("the element must be a type of operation");

            this.operationXml = operationXml;
        }

        public IOperation Build()
        {

            operationXml.MoveToFirstChild();
            //go to the appPart element
            XPathNavigator appPartNav = operationXml.CreateNavigator();
            AppPart appPart = new AppPartBuilder(appPartNav).Build();
            //go the operation type element
            operationXml.MoveToNext("type", "");
            string opType = operationXml.InnerXml.Trim();
            IOperation operationInstance = CreateByType(opType, appPart);

            return operationInstance;
        }

        IOperation CreateByType(string type, AppPart part)
        {
            IOperation op = null;
            switch (type.ToLower())
            {
                case "create":
                    op = new Creation(part);
                    break;
                case "rename":
                    op = new Rename(part);
                    break;
                case "delete":
                    op = new Delete(part);
                    break;
                case "move":
                    op = new Move(part);
                    break;
                default:
                    throw new Exception("unsupported operation type");
            }
            return op;
        }

        XPathNavigator operationXml;
    }

}
